package com.jshoperxms.controller.mall.backstage.promotion;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.products.ProductSearchResultVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.GoodsCommentT;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.entity.PromotionProductAlbumContentT;
import com.jshoperxms.entity.PromotionProductAlbumT;
import com.jshoperxms.service.ProductTService;
import com.jshoperxms.service.PromotionProductAlbumContentTService;
import com.jshoperxms.service.PromotionProductAlbumTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 16/12/12.
 * Des:
 */
@Controller
@RequestMapping("/mall/promotion/productalbumcontent")
public class PromotionProductAlbumContentTController extends BaseTController implements IBaseCtrl<PromotionProductAlbumContentT> {

    @Resource
    private PromotionProductAlbumContentTService promotionProductAlbumContentTService;

    @Resource
    private PromotionProductAlbumTService promotionProductAlbumTService;
    @Resource
    private ProductTService productTService;
    private Map<String,Object> responsedata=new HashMap<>();


    //单个添加专辑商品,有介绍+商品信息
    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody PromotionProductAlbumContentT rq) throws ParseException {
        if(StringUtils.isBlank(rq.getPromotionProductAlbumId())&&StringUtils.isBlank(rq.getProductid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            PromotionProductAlbumContentT bean=new PromotionProductAlbumContentT();
            PromotionProductAlbumT ppa=this.promotionProductAlbumTService.findByPK(PromotionProductAlbumT.class,rq.getPromotionProductAlbumId());
            if(ppa!=null){
                bean.setVol(ppa.getVol());
            }else{
                bean.setVol(StaticKey.EMPTY);
            }
            bean.setId(this.serial.Serialid(SerialKeys.PROMOTIONPRODUCTALBUMCONTENT));
            bean.setPromotionProductAlbumId(rq.getPromotionProductAlbumId());
            bean.setSectiontitle(rq.getSectiontitle());
            bean.setContent(rq.getContent());
            bean.setCreatorid(BaseTools.getAdminCreateId());
            bean.setCreatetime(DateTools.getSystemTimeBi());
            bean.setDes(rq.getDes());
            Map<String,String>map= BaseTools.parseImg(rq.getMainimg());
            bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
            bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
            bean.setStatus(rq.getStatus());
            bean.setUpdatetime(DateTools.getSystemTimeBi());
            bean.setVersiont(1);
            bean.setProductid(rq.getProductid());
            this.promotionProductAlbumContentTService.save(bean);
            responsedata.put(TagWords.SUCCESS, true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    /**
     * 获取专辑下的所有商品内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody PromotionProductAlbumContentT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            PromotionProductAlbumContentT bean=this.promotionProductAlbumContentTService.findByPK(PromotionProductAlbumContentT.class,rq.getId());
            if(bean!=null){
                ImgFileBean ifb=new ImgFileBean();
                ifb.setNormalfilepath(bean.getMainimg());
                ifb.setCompressfilepath(bean.getSmainimg());
                ifb.setBasepath(StaticKey.EMPTY);
                List<ProductSearchResultVo> beanlist = new ArrayList<>();
                ProductT p=this.productTService.findByPK(ProductT.class,bean.getProductid());
                if(p!=null) {
                    ProductSearchResultVo psv = new ProductSearchResultVo();
                    psv.setId(p.getProductid());
                    psv.setGoodsid(p.getGoodsid());
                    psv.setMainimg(p.getMainimg());
                    psv.setPsn(p.getPsn());
                    psv.setProductname(p.getProductname());
                    psv.setNname(p.getNname());
                    psv.setGoodstypename(p.getGoodstypename());
                    psv.setStock(p.getStock() + StaticKey.EMPTY);
                    psv.setSaleprice(p.getSaleprice().toString());
                    psv.setMemberprice(p.getMemberprice().toString());
                    psv.setSalestatus(p.getSalestatus());
                    psv.setBrandname(p.getBrandname());
                    beanlist.add(psv);
                }

                responsedata.put(TagWords.IFB,ifb);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.BEANLIST,beanlist);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody PromotionProductAlbumContentT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(),TagWords.SPLITDOT);
            for(String s:ids){
                PromotionProductAlbumContentT bean=this.promotionProductAlbumContentTService.findByPK(PromotionProductAlbumContentT.class,s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.promotionProductAlbumContentTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }



    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody PromotionProductAlbumContentT rq) throws ParseException {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            PromotionProductAlbumContentT bean=this.promotionProductAlbumContentTService.findByPK(PromotionProductAlbumContentT.class,rq.getId());
            if(bean!=null){
                bean.setSectiontitle(rq.getSectiontitle());
                bean.setContent(rq.getContent());
                bean.setDes(rq.getDes());
                Map<String,String>map= BaseTools.parseImg(rq.getMainimg());
                bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
                bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
                bean.setStatus(rq.getStatus());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                bean.setProductid(rq.getProductid());
                this.promotionProductAlbumContentTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }


    /**
     * 根据专辑id获取专辑所有内容
     * @param searchModel
     * @param search
     * @param ordervalue
     * @param ordertype
     * @return
     */
    @RequestMapping(value="/findPaContentByAlbumIdByPage",method= RequestMethod.POST)
    public ResponseEntity findPaContentByAlbumId(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findOnePaContentCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    private void findOnePaContentCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getPromotionProductAlbumId())){
                criterion=Restrictions.and(criterion).add(Restrictions.eq("promotionProductAlbumId",searchModel.getPromotionProductAlbumId()));
            }
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("sectiontitle",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("sectiontitle",search,MatchMode.ANYWHERE));
            }
            int records=this.promotionProductAlbumContentTService.count(PromotionProductAlbumContentT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<PromotionProductAlbumContentT> list = this.promotionProductAlbumContentTService.findByCriteriaByPage(
                    PromotionProductAlbumContentT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);

        }else{
            if(StringUtils.isNotBlank(search)){
                filterOnePaContentSearch(searchModel,search);
            }else{
                findOnePaContentDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }


    private void filterOnePaContentSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        if(StringUtils.isNotBlank(searchModel.getPromotionProductAlbumId())){
            criterion=Restrictions.and(criterion).add(Restrictions.eq("promotionProductAlbumId",searchModel.getPromotionProductAlbumId()));
        }
        criterion=Restrictions.and(criterion).add(Restrictions.like("sectiontitle",search,MatchMode.ANYWHERE));
        int records=this.promotionProductAlbumContentTService.count(PromotionProductAlbumContentT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<PromotionProductAlbumContentT> list = this.promotionProductAlbumContentTService.findByCriteriaByPage(
                PromotionProductAlbumContentT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }



    private void findOnePaContentDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        if(StringUtils.isNotBlank(searchModel.getPromotionProductAlbumId())){
            criterion=Restrictions.and(criterion).add(Restrictions.eq("promotionProductAlbumId",searchModel.getPromotionProductAlbumId()));
        }
        int records=this.promotionProductAlbumContentTService.count(PromotionProductAlbumContentT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order= BaseTools.orderByParam(TagWords.UPDATETIME,ordervalue,ordertype);
        List<PromotionProductAlbumContentT> list = this.promotionProductAlbumContentTService.findByCriteriaByPage(
                PromotionProductAlbumContentT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }


    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        return null;
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {

    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {

    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {

    }

    @Override
    public void processPageList(List<PromotionProductAlbumContentT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for(PromotionProductAlbumContentT bean:list){
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id",bean.getId());
            cellMap.put("smainimg",bean.getSmainimg());
            cellMap.put("sectiontitle",bean.getSectiontitle());
            cellMap.put("content",bean.getContent());
            cellMap.put("productid",bean.getProductid());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA,data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
